<?
//languagepack for mailsystem
?>
<script type="text/javascript" src="lib/jquery/jquery.disable.text.select.js"></script>
       <script language="javascript" src="lib/jquery/jquery.dimensions.js"></script>
        <script language="javascript" src="lib/jquery/jquery.bgiframe.js"></script>
        <script type="text/javascript" src="lib/jquery/jquery.suggest.js"> </script>
<script type="text/javascript">
    var mailcontainer, lastMail, strg_down, shift_down, mouse_down, selected=0, selectedfolder=0, allowcopy, windowcount=0;
    var mails_gesamt=0, mails_seite=1, mails_perpage=25;
	foldername= new Array();
    foldername[0]="<?echo $lang[mail_inbox]?>";
	foldername[-1]="<?echo $lang[mail_outbox]?>";
	readed=new Array();
	function debugmsg(msg){
		//console.log(msg);
	}
	$(function(){
	
		//##########################################Folderlist Funktionen		
		function loadFolderlist(){
            $.post("ajax.php", { mod: "mail", task: "showfolders" }, function(xmldata){
				$("#folderlist ul").html("");
                $('folder', xmldata).each(function(i) {
						folder_id = $(this).find("id").text();					
                    folder_name = $(this).find("name").text();
					foldername[folder_id]=folder_name;
                    $("#folderlist ul").append(
                        "<li folder=\"" + folder_id + "\" class=\"folder\">" + folder_name + "</li>"
                    );
                });	
				//mouseupevent für das Kopieren
				$('.folder').mouseup(function(){
					if(selected>0 && allowcopy && selectedfolder>=0){
						var ziel=$(this).attr("folder");
						var mails="";
						$(".selected").each(function(){
							mails+="|"+$(this).attr("mail");
						});							
						$.post("ajax.php", {mod: "mail", task: "copymails", mails: mails, ziel: ziel}, function(answer){
							if(answer=="ok"){
								$(".selected").fadeOut(500, function(){$(this).remove()});
    							if(selected>10) loadFolder(selectedfolder, mails_seite);

								selected=0;
							}
						});					
					}else{
						loadFolder($(this).attr("folder"));
					}
				});	//ende selected =0					
			});	//ende der ajaxabfrage
		}//ende load folderlist

		function newFolder(){
			if(folder=prompt("Ordnername:","")){
	            $.post("ajax.php", {mod: "mail", task: "newfolder", foldername: folder}, function(response){
					if(response=="ok") loadFolderlist();
				});
			}
		}

		function deleteFolder(){
			if(confirm("<?echo $lang[mail_folder_delete]?>")){
				$.post("ajax.php", {mod: "mail", task: "deletefolder", folder: selectedfolder}, function(response){
					if(response=="ok") loadFolderlist();
				});
			}
		}

		//##########################################Optionen laden
		function loadOptions(){
			var html="<b>Options:</b><br>";
			if(selected==1) html+="<input type=\"button\" id=\"optionDeleteMail\" value=\"<?echo $lang[mail_option_delete_mail]?>\" /><br>";
			if(selected>1) html+="<input type=\"button\" id=\"optionDeleteMail\" value=\"<?echo $lang[mail_option_delete_mails]?>\" /><br>";
			html+="<input type=\"button\" id=\"optionNewFolder\" value=\"<?echo $lang[mail_option_new_folder]?>\"/><br>";
			if(selectedfolder>0) html+="<input type=\"button\" id=\"optionDeleteFolder\" value=\"<?echo $lang[mail_option_delete_folder]?>\" /><br>";
			$("#options").html(html);	
			//setzen der Optionen
			$("#optionDeleteMail").click(function(){
				deleteMails();
			}); //end of optionDeleteMail
			$("#optionNewFolder").click(function(){
				newFolder();
			}); //end of optionNewFolder
			$("#optionDeleteFolder").click(function(){
				deleteFolder();
			}); //end of optionDeleteFolder			
		}

		//##########################################Mail anzeigen optionen
		function loadFolder(folder, seite){ //Loading folder content to mailcontainer
            $("#whereami").html("<img src=\"images/ajax-loader.gif\">");
			if(selectedfolder!=folder) seite=1;
			mails_seite=seite;
            $.post("ajax.php", {mod: "mail", task: "showmails", folder: folder, seite:seite}, function(xml){
				mailcontainer=xml;
				selectedfolder=folder;
				displayMails();
				if(folder>=0) $("#rowMailPartner").html("<?echo $lang[mail_sender]?>");
				else $("#rowMailPartner").html("<?echo $lang[mail_receptor]?>");
				$("#whereami").html("<?echo $lang[mail_folderview]?> \""+foldername[folder]+"\"");
			});		
		}
		
		function search(){
			var searchstring=prompt("<?echo $lang[mail_search]?>:","");
			$.post("ajax.php", {mod: "mail", task: "showmails", search: searchstring}, function(xml){
				mailcontainer=xml;
				displayMails();
				$("#whereami").html("<?echo $lang[mail_searchresult]?> \""+searchstring+"\"");
			});		
		}
		
        function leiste(){
            var lhtml="";
            for(var i=1; i<=mails_gesamt/mails_perpage;i++){
                lhtml+="[<a class=\"leiste\" id=\"lseite"+i+"\">"+i+"</a>]";
            }
               
            $(".navileiste").html(lhtml);
			$(".leiste").css("color","gray");
            $("#lseite"+mails_seite).css("color","white");
            $(".leiste").click(function(){
			   mails_seite=$(this).html();
               loadFolder(selectedfolder, mails_seite);
            });
        
        }

		function displayMails(){ //display emails in #mailtable (loading from mailcontainer) ### + additional events ###
			debugmsg("converting XML-File");
			$(".mail").remove();
            mails_gesamt=$('info', mailcontainer).find("anzahl").text();
			var mailcount=0;
			$('mail', mailcontainer).each(function(i) {
				debugmsg("lade mail");
				mail_id = $(this).find("id").text();
				mail_betreff = $(this).find("betreff").text();				
				mail_absenderid = $(this).find("absenderid").text();
				mail_absendername = $(this).find("absendername").text();
				mail_gelesen = $(this).find("gelesen").text();
				mail_zeit = $(this).find("zeit").text();
				mail_typ = $(this).find("typ").text();
				if(mail_gelesen==0) var gelesen="ungelesen";
				else var gelesen="";
                
				if(mail_absenderid==0) absenderfeld=mail_absendername;
				else absenderfeld="<a href=\"game.php?page=spielerinfo&id="+mail_absenderid+"\">" + mail_absendername + "</a>";
				$("#mailtable").append(
					"<tr class=\"mail "+gelesen+"\" mail=\"" + mail_id + "\" mailtyp=\""+mail_typ+"\">"
						+ "<td>" + mail_betreff + "</td>"
						+ "<td>"+absenderfeld+"</td>"
						+ "<td>" + mail_zeit + "</td>"
					+ "</tr>");	
				mailcount++;
			});
			loadOptions();		
			//Mail-Events
			$('.mail').click(function(){ //Script to handle different selections
				mailClick(this);
			});															
			$('.mail').dblclick(function(){ //Open mail by double click
				openMail($(this).attr("mail"));
			});
            leiste();
		};	

		function mailClick(me){
			if(strg_down){
				$(me).toggleClass("selected");
			}else if(shift_down){
				selectMails($(me), lastMail);				
			}else{
				$(me).nextAll().removeClass("selected");
				$(me).prevAll().removeClass("selected");
				$(me).toggleClass("selected");				
			}
			selected=$(".selected").length;
			debugmsg(selected+" selected");
			$("#copytooltip").html("Copy "+selected+" Mails to");
			lastMail=$(me);
			loadOptions();		
		}
		
		function selectMails(from, target){ //Multiselect with SHIFT
			debugmsg("trying multiselect "+from+" -> "+target);
			$('.mail').removeClass("selected");
			from=$("#mailtable tr").index(from);
			target=$("#mailtable tr").index(target);
			if(from>target){
				var i=from;
				from=target;
				target=i;
				debugmsg("reverse order");
			}
			debugmsg("from "+from+" to "+target);
			if(from==0) from=1; //disable headline selection
			for(i=from; i<=target; i++){
				$("#mailtable tr:nth-child("+(i+1)+")").addClass("selected");
			}
		}

		function openMail(id){
			//lade Maildaten
            var subject=$("mail[id="+id+"]",mailcontainer).find("betreff").text();
            var absender=$("mail[id="+id+"]",mailcontainer).find("absendername").text();
            var gelesen=$("mail[id="+id+"]",mailcontainer).find("gelesen").text();
            var typ=$("mail[id="+id+"]",mailcontainer).find("typ").text();
			if(typ<2){
				var mailtext=$("mail[id="+id+"]",mailcontainer).find("text").text();
				mailtext = mailtext.split("[br]").join("<br>");
			}else{
				var mailtext="loading content...";
				$.post("ajax.php",{mod:"mailcontent",id:id},function(html){
					$('#dialog'+id).html(html);
				});
			}
		    //Mail fals nötig als gelesen markieren	
			if(gelesen==0 && !readed[id]){
				$.post("ajax.php", {mod: "mail", task: "read", mail: id}, function(answer){
					if(answer=="ok"){
						$(".mail[mail="+id+"]").removeClass("ungelesen");
						readed[id]=true;
						$("#igm").text($("#igm").text()-1);
					}				
				});
			}
			$('body').append('<div id="dialog'+id+'" title="<?echo $lang[mail_subject]?>: '+subject+'" style="overflow:scroll; text-align:left;">Text</div>');
            if (typ<2) {
                $('#dialog'+id)
                .dialog({ width: 600, minWidth: 400, height: 300, buttons: { 
                "<?echo $lang[mail_option_close]?>": function() { $(this).dialog("close"); },
                "<?echo $lang[mail_option_delete]?>": function() { deleteMail(id, this); },
                "<?echo $lang[mail_option_reply]?>": function() { 
                    newIgm(absender, "Re: "+subject);
                    } 
                } })
                
                .html(mailtext)
                .bind('dialogclose', function(event, ui) {
                    $('#dialog'+id).remove();
                });
            } else {
                $('#dialog'+id)
                .dialog({ width: 600, minWidth: 400, height: 300, buttons: { 
                "<?echo $lang[mail_option_close]?>": function() { $(this).dialog("close"); },
                "<?echo $lang[mail_option_delete]?>": function() { deleteMail(id, this); }
                } })
                
                .html(mailtext)
                .bind('dialogclose', function(event, ui) {
                    $('#dialog'+id).remove();
                });            
            }
		}
		
		function deleteMail(id, fenster){
			debugmsg("deleteMail("+id+","+fenster+")");
			$.post("ajax.php", {mod: "mail", task: "deletemail", mail: id}, function(answer){
				if(answer=="ok"){
					$(".mail[mail="+id+"]").fadeOut(500, function(){$(this).remove()});
					$(fenster).fadeOut(500, function(){$(this).dialog("close");});
				}
			});					
		}
		
		function deleteMails(){
			var ziel=$(this).attr("folder");
			var mails="";
			$(".selected").each(function(){
				mails+="|"+$(this).attr("mail");
			});							
			var conf;
			if(selected>1) conf=confirm("<?echo $lang[mail_mail_delete]?>");
			else conf=true;
			if(conf){
				$.post("ajax.php", {mod: "mail", task: "deletemails", mails: mails, ziel: ziel}, function(answer){
					if(answer=="ok"){
						$(".selected").fadeOut(500, function(){$(this).remove()});
						if(selected>10) loadFolder(selectedfolder, mails_seite);
						selected=0;
					}
				});					
			}
		}

		
		function newIgm(empfaenger, subject){
			windowcount++;
			var id=windowcount;
			$('body').append('<div id="nMail'+id+'" title="<?echo $lang[mail_new_igm]?>" style="overflow:scroll; text-align:left;"></div>');
			var html='<form id="mailform'+id+'">';
			html+='<input type="hidden" name="mod" value="mail"/>';
			html+='<input type="hidden" name="task" value="sendmail"/>';
			html+='<table>';
			html+='  <tr>';
			html+='    <th><?echo $lang[mail_receptor]?>:</th>';
			html+='    <td><input type="text" name="empfaenger" value="'+empfaenger+'" /></td>';
			html+='  </tr>';
			html+='  <tr>';
			html+='    <th><?echo $lang[mail_subject]?>:</th>';
			html+='    <td><input type="text" name="betreff" value="'+subject+'" maxlength="30"/></td>';
			html+='  </tr>';
			html+='</table>';
			html+='<textarea name="text" id="mailtext'+id+'" style="width:100%;"></textarea>';
			html+='</form>';
			$('#nMail'+id)
			.dialog({ width: 600, minWidth: 350, height: 350, minHeight: 350, buttons: { 
					"<?echo $lang[mail_option_close]?>": function() { $(this).dialog("close"); },
					"<?echo $lang[mail_option_send]?>": function() { sendmail(id); }
				} 
			})		
			.bind('dialogclose', function(event, ui) {
				$('#nMail'+id).remove();
			})
			.html(html);
			
			$('#nMail'+id).bind('resize', function(event, ui) {
				debugmsg("resize window");
				$('#mailtext'+id).height($('#nMail'+id).height()-100);
			});

			//height of textarea
			$('#mailtext'+id).height($('#nMail'+id).height()-100);
			//searchbox
			jQuery('#mailform'+id+' input[name=empfaenger]').suggest("ajax.php?mod=suggest_users&filter=<?echo $_SESSION[server][Id]?>",{});		
		}//end of newIGM

		function sendmail(fensterId){
			$.post("ajax.php", $('#mailform'+fensterId).serializeArray() , function(answer){
                if(answer=="ok"){
                    $("#nMail"+fensterId).hide(500,function(){
                        $("#nMail"+fensterId).dialog("close");
                    });
                }else if(answer=="#1"){
                    alert("<?echo $lang[mail_sendmail_error1]?>");
                }else if(answer=="#2"){
                    alert("<?echo $lang[mail_sendmail_error2]?>");
                }else if(answer=="#3"){
                    alert("<?echo $lang[mail_sendmail_error3]?>");
                }else{
                    alert("<?echo $lang[mail_sendmail_erroru]?>");
                }                
			});
		}	

	    
	
		//####Funktionen den Elementen zuweisen
		$.ui.dialog.defaults.bgiframe = true;
		$('#mailtable').disableTextSelect();
		$("#mailtable").mouseenter(function(){
			allowcopy=true;
		});
		$("#mailtable").mouseleave(function(){
			if(!mouse_down) allowcopy=false;
		});
		$("#newMail").click(function(){newIgm("","")});
		$("#search").click(function(){search()});
		$("#refresh").click(function(){loadFolder(selectedfolder)});

		$("#labelNormal").click(function(){toggleLabel(0)});
		$("#labelAlly").click(function(){toggleLabel(1)});
		$("#labelSystem").click(function(){toggleLabel(2)});
		$("#labelInfo").click(function(){toggleLabel(3)});
        $("#labelAll").click(function(){
            $(".mail").toggleClass("selected");
            selected=$(".selected").length;
   			$("#copytooltip").html("Copy "+selected+" Mails to");    
        });
        
		
		
		//##########################################EVENTS abfragen
		//###Keyevents
		$(document).keydown(function(event){ //handle keydown events
			debugmsg("key down ->"+event.keyCode);
			if(event.keyCode==17 && !strg_down){ //STRG pressed
				strg_down=true;
			    debugmsg("STRG is now down");
				return false;
			}
			if(event.keyCode==16 && !shift_down){ //STRG pressed
				shift_down=true;
			    debugmsg("SHIFT is now down");
				return false;
			}
		});
		
        $(document).keyup(function(event){ //handle keyup events
			debugmsg("key up ->"+event.keyCode);
			if(event.keyCode==17 && strg_down){ //STRG pressed
				strg_down=false;
			    debugmsg("STRG is now up");
				return false;
			}
			if(event.keyCode==16 && shift_down){ //STRG pressed
				shift_down=false;
			    debugmsg("SHIFT is now up");
				return false;
			}						
			if(event.keyCode==46){ //DEL pressed
				if(selected>0) deleteMails();
			}
			if(event.keyCode==65){
				if(strg_down) $(".mail").addClass("selected");
			}
		});
        
        function toggleLabel(id){
            $(".mail[mailtyp="+id+"]").toggleClass("selected");        
            selected=$(".selected").length;
   			$("#copytooltip").html("Copy "+selected+" Mails to");

        }
		//###Mouseevents
        $(document).mouseup(function(event){
		    if(selectedfolder>=0){
				debugmsg("mouse up ("+ event.clientX+", "+ event.clientY+")");
				mouse_down=false;
				$('#copytooltip').stop().hide(0);	
			}
		});
		
		$(document).mousemove(function(e) {
			$("#copytooltip").css('top', e.pageY + 10).css('left', e.pageX + 10);
		});
	
        $("#mailtable").mousedown(function(event){
			debugmsg("mouse down ("+ event.clientX+", "+ event.clientY+")");
			mouse_down=true;
			if(selected>0 && selectedfolder>=0) $('#copytooltip').stop().show(0);
		});
	
        <?
        if($_REQUEST[mailto]>0){
            $db->query("SELECT Id, Name FROM spieler WHERE Id=".intval($_REQUEST[mailto]).";");
            if($ziel=$db->fetch_assoc()){
                echo "newIgm(\"$ziel[Name]\",\"\");";
            }
        }
        ?>	
		//###################################### Funktionsauführungen bei Start
		loadFolderlist();
		loadFolder(0,1);	
        loadOptions();		
	});//End of jquery
</script>
<style type="text/css">

	.tabs{background-color:darkgray;}
    .tabs li{float:left; width:140px; background-color:gray; display:block;}
	#foldercol{width:30%;}
	#folderlist{list-style-image:url(images/ordner.gif); }
	#folderlist ul{padding-left:20px;}
	.folder:hover{background-color:gray;}
	#copytooltip{position:absolute; display:none; background-color:silver; width:150px;}
	#mails{vertical-align:top;}
	.mailcontent{text-align:left;  border:1px solid #7C4F04; min-height:140px;}
	#folder{vertical-align:top;}
	#mails {padding:0;}
	
	#mailtable{width:100%;}
	#mailtable td{border:0px solid gray;}
	#mailtable th{border:1px solid gray; cursor:pointer; background-image:none; background-color:#231B18; }
	#mailtable .mail{}
    .selected{background-color:silver; color:red;}
	.ungelesen{font-weight:bold;}
	
	.ac_results {
		border:1px solid #221A17;
        
        background-color:#1d1512;
        color: white;
		padding: 0;
		margin: 0;
		list-style: none;
		position: absolute;
		z-index: 10000;
		display: none;
	}
	
	.ac_results li {
		padding: 2px 5px;
		white-space: nowrap;
		color: white;
		text-align: left;
	}
	
	.ac_over {
		cursor: pointer;
	}
	
	.ac_match {
		font-weight: bold;
        color: #b77d12;
	}
	
</style>
<h1><?echo $lang[mail_headline]?></h1>
<table width="100%" class="tabelle">
	<tr class="tabelle_head" style="text-align:left;">
		<td>
			<input type="button" id="newMail" value="<?echo $lang[mail_newmail]?>"/>
			<input type="button" id="search" value="<?echo $lang[mail_option_search]?>" />
			<input type="button" id="refresh" value="<?echo $lang[mail_option_refresh]?>" />
		</td>
		<td id="whereami">
		</td>
	</tr>
	<tr>
		<td id="foldercol" valign="top" height="50px">
			<ul id="folderlist">
				<li folder="0" class="folder"><?echo $lang[mail_inbox]?></li>
				<ul></ul>
				<li folder="-1" class="folder"><?echo $lang[mail_outbox]?></li>				
			</ul>
		</td>
		<td id="mails" rowspan="3" valign="top">		
			<table id="mailtable">
				<tr>
					<th width="60%"><?echo $lang[mail_subject]?></th>
					<th width="20%" id="rowMailPartner"><?echo $lang[mail_sender]?></th>
					<th width="20%"><?echo $lang[mail_date]?></th>
				</tr>
			</table>		
		</td>
	</tr>
	<tr>
		<td id="options" valign="top" height="40px"></div>
    </tr>
    <tr>
        <td  valign="top">
          <b>Label:</b>
          <a id="labelAll"><u>all</u></a>
          <a id="labelNormal"><u>normal</u></a>
          <a id="labelAlly"><u>allianz</u></a>
          <a id="labelSystem"><u>berichte</u></a>
          <a id="labelInfo"><u>system</u></a>
        </td>      
	</tr>
    <tr>
        <th colspan="2" class="navileiste" align="center"></th>
    </tr>
</table>
<div id="copytooltip"></div>

